SET NOCOUNT ON;
declare @release smallint = 5;
declare @version smallint = 0;
declare @script_name varchar(256);
declare @script_type varchar(20)='CensusData';
set @script_name=@script_type+'_V'+convert(varchar(5),@version)+'R'+right('00000'+convert(varchar(5),@release),5)+'.sql'

if exists (select 1 from dbo.database_version_information where script_name=@script_name and undone=0)
	print 'script '+@script_name+' already executed, please undo then re-execute.';
else
begin try
begin tran
/*--Begin Code Here --*/

declare @row_count int;
declare @expected_row_count int;

if exists (select * from sys.tables where object_id=object_id('dbo.ACSSF_Load_Control'))
	drop table dbo.ACSSF_Load_Control;

create table dbo.ACSSF_Load_Control (
Table_Name sysname not null
,Sample_Set_Code char(6) not null
,Load_Successful_Flag bit not null
,Expected_Record_Count int not null
,Record_Count int null
,Validated_Date datetime null
,constraint PK_dbo__ACSSF_Load_Control primary key (Table_Name,Sample_Set_Code)
)
insert into dbo.ACSSF_Load_Control 
values
('Geography_File','2013e1',0,7801,NULL,NULL)
,('Geography_File','2012e1',0,7750,NULL,NULL)
,('Summary_File_0001','2013e1',0,7801,NULL,NULL)
,('Summary_File_0001','2012e1',0,7750,NULL,NULL)

select @row_count=count(*) from ACSSF.Geography_File;
update dbo.ACSSF_Load_Control 
set Record_Count = @row_count
,Validated_Date =getdate()
,Load_Successful_Flag =1
where
Table_Name='Geography_File'
and
Sample_Set_Code='2013e1'
and
Expected_Record_Count =@row_count 
;

select @row_count=count(*) from ACSSF.Summary_File_0001;
update dbo.ACSSF_Load_Control 
set Record_Count = @row_count
,Validated_Date =getdate()
,Load_Successful_Flag =1
where
Table_Name='Summary_File_0001'
and
Sample_Set_Code='2013e1'
and
Expected_Record_Count =@row_count 
;

/*--End Code Here --*/
if exists (select 1 from dbo.database_version_information where script_name=@script_name and undone=1)
	update dbo.database_version_information 
	set undone=0
	,date_released=getdate()
	where
	script_name=@script_name;
else
	insert into dbo.database_version_information 
	values(@script_name,@script_type,@version,@release,GETDATE(),0);
	
print 'script '+@script_name+' succeeded!'
commit tran
end try
begin catch 
	declare @error_message varchar(2000);
	set @error_message='SCRIPT:'+@script_name+' FAILED! ROLLBACK!  ERROR_MESSAGE:'
	+coalesce(error_message(),'')+' ERROR_NUMBER:'+coalesce(convert(varchar(10),error_number()),'');
	ROLLBACK
	raiserror(@error_message,16,1)
end catch
